package com.graduation.community_manager.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wdh
 */
public class JWTUtil {
    //定义密钥
    public static final String SECRET = "XASDAS";
    //定义token的有效时间
    public static final int EXPIRED  = 1000*1000;
    public static final int REFREASH_TIME = 1000*1000;
    public static final String ACCOUNT ="account";

    static Map<String, Object> cacheTokens = new HashMap<>();

    //存储token
    public static void saveToken(String token, long time){
        cacheTokens.put(token,time);
    }

    // 拿到token的创建时间
    public static Object getTime(String token){
        return cacheTokens.get(token);
    }

    // 删除token
    public static void removeToken(String token){
        cacheTokens.remove(token);
    }

    // 查找是否包含对应的token
    public static boolean containsToken(String token){
        return cacheTokens.containsKey(token);
    }



    //创建toke
    public static String createToken(String account, long time){
        try {
            //根据密码创建算法，secret是密钥，可以自定义
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //创建token，Issuer是token的拥有人，可以自定义
            String token = JWT.create()
                    .withClaim(ACCOUNT,account)
                    .withExpiresAt(new Date(time+EXPIRED))
                    .sign(algorithm);
            return token;
        } catch (JWTCreationException exception){
            exception.printStackTrace();
            throw exception;
        }
    }

    //验证token
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception){
            //Invalid signature/claims

            exception.printStackTrace();
            throw exception;
        }
    }

    public static String getAccount(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            //获取自定义参数
            String account =  jwt.getClaim(ACCOUNT).asString();
            return account;
        } catch (JWTDecodeException exception){
            //Invalid token
            exception.printStackTrace();
            throw exception;
        }
    }
}
